<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>
      水龙头测试
      <button @click="get">获取 0.5 ether</button>
    </p>
  </div>
</template>

<script>
import Web3 from 'web3'
import contract from '@truffle/contract'
import FaucetJson from './Faucet.json'
export default {
  data () {
    return {
      web3: false,
      contract_instance: false,
      accounts: []
    }
  },
  async created () {
    // 初始化web3
    // Modern dapp browsers...
    let web3Provider
    if (window.ethereum) {
      web3Provider = window.ethereum
      try {
        // Request account access
        await window.ethereum.enable()
      } catch (error) {
        // User denied account access...
        console.error('User denied account access')
      }
    } else if (window.web3) {
      web3Provider = window.web3.currentProvider
    } else {
      web3Provider = new Web3.providers.HttpProvider('http://localhost:7545')
    }
    this.web3 = new Web3(web3Provider)
    // 初始化合约
    const FaucetContract = contract(FaucetJson)
    FaucetContract.setProvider(web3Provider)
    this.contract_instance = await FaucetContract.deployed()
    this.accounts = await this.web3.eth.getAccounts()
  },
  methods: {
    get () {
      // 调用合约的withdraw函数
      this.contract_instance.withdraw(this.web3.utils.toWei('0.5', 'ether'), { from: this.accounts[0] })
    }
  },
  name: 'HelloWorld',
  props: {
    msg: String
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
